﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Runtime.InteropServices;
using System.Web.ModelBinding;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml.Linq;
using VietTrips.Domain.Interfaces;
using VietTrips.Domain.Models;
using VietTrips.Domain.Repositories;
using VietTrips.Domain.Services;
using VietTrips.WebUI.Helpers;
using PagedList;

namespace VietTrips.WebUI.Areas.Management.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class UserManagerController : Controller
    {
        private readonly UserManagerService _userManager;

        public UserManagerController()
        {
            _userManager = new UserManagerService();
        }

        //
        // GET: /Management/UserManager/
        // Nơi lấy dự liệu tạo thành bảng user
        public ActionResult UsersList(int? page = 1, 
            string rowsPerPage = "10", 
            string role = null, 
            string sortOrder = null,
            string currentFilter = null,
            string searchText = null)
        {
            try
            {
                ViewBag.CurrentSort = sortOrder;
                ViewBag.CurrentRole = role;
                ViewBag.UsernameSortParm = String.IsNullOrEmpty(sortOrder) ? "Username_desc" : "";
                ViewBag.FullnameSortParm = sortOrder == "Fullname" ? "Fullname_desc" : "Fullname";
                ViewBag.EmailSortParm = sortOrder == "Email" ? "Email_desc" : "Email";
                ViewBag.DateSortParm = sortOrder == "Date" ? "Date_desc" : "Date";

                if (searchText != null)
                {
                    page = 1;
                }
                else
                {
                    searchText = currentFilter;
                }
                ViewBag.CurrentFilter = searchText;
                List<UserProfile> viewModel = null;
                
                // Nếu có phân trang thì dựa vào số trang (pageNumber) và số dòng mỗi trang (rowsNumber), nếu không thì get hết
                viewModel = 
                        role != null ?
                            _userManager.GetAllUsers(role, sortOrder) :
                        searchText != null ?
                            _userManager.SearchUsers(searchText, sortOrder) :
                            _userManager.GetAllUsers(sortOrder);

                ViewBag.UsersCount = viewModel.Count();

                int pageNumber = (page ?? 1);
                int pageSize = PageNumberHelper.ConvertObjectToInt(rowsPerPage, ViewBag.UsersCount);
                ViewBag.Page = pageNumber;
                ViewBag.RowsPerPage = pageSize;

                return View(viewModel.ToPagedList(pageNumber, pageSize));            
            }
            catch (Exception)
            {
                throw;
            }
        }

        //
        // GET: /Management/UserManager/Details/5

        public ActionResult UserDetails(int id)
        {
            return RedirectToAction("Dashboard", "Admin");
        }

        //
        // GET: /Management/UserManager/Edit/5

        public ActionResult EditUser(int id)
        {
            if (id != default(int))
            {
                UserProfile viewModel = _userManager.GetUser(id);
                ViewBag.provinces = GetProvinces();
                return View(viewModel);
            }
            return RedirectToAction("UsersList");
        }

        //
        // POST: /Management/UserManager/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditUser(UserProfile userProfile)
        {
            try
            {
                _userManager.UpdateUser(userProfile);
                return RedirectToAction("EditUser");
            }
            catch
            {
                ViewBag.StatusMessage = "Thay đổi thông tin không thành công.";
                return RedirectToAction("EditUser");
            }
        }

        //
        // POST: /Management/UserManager/ManageUsers?page=1&rowsPerPage=10&role=all&sortOrder=Date_desc&currentFilter=yến
        // Nơi thực hiện các lệnh xoá, thăng cấp, vv
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ManageUsers(int? page = 1,
            string rowsPerPage = "10",
            string role = null,
            string sortOrder = null,
            string currentFilter = null,
            string searchText = null,
            [Form] string[] checkboxes = null,
            [Form] string action = "",
            [Form] string changeToRole = null)
        {
            try
            {
                if (checkboxes != null)
                {
                    var ids = new List<int>();
                    foreach (var checkbox in checkboxes)
                    {
                        int temp;
                        if (Int32.TryParse(checkbox, out temp))
                        {
                            ids.Add(temp);
                        }
                    }

                    ViewBag.Status = "success";
                    if (ids.Count > 0 && action == "Delete")
                    {
                        _userManager.MarkDeletedUsers(ids);
                        ViewBag.StatusMessage = "Thao tác xoá người dùng thành công.";
                    }
                    else if (ids.Count > 0 && action == "CancelDelete")
                    {
                        _userManager.UnmarkDeletedUsers(ids);
                        ViewBag.StatusMessage = "Thao tác bỏ lệnh xoá người dùng thành công.";
                    }
                    else if (ids.Count > 0 && action == "ChangeRole")
                    {
                        ViewBag.StatusMessage = "Thay đổi quyền hạn người dùng thành công.";
                    }
                    else
                    {
                        ViewBag.StatusMessage = "Bạn chưa chọn gì để xoá.";
                        ViewBag.Status = "warning";
                    }
                }

                return RedirectToAction("UsersList", new
                {
                    page = page,
                    rowsPerPage = rowsPerPage,
                    role = role,
                    sortOrder = sortOrder,
                    currentFilter = currentFilter,
                    searchText = searchText
                });
            }
            catch (Exception ex)
            {
                ViewBag.StatusMessage = "Có sự cố xảy ra: " + ex.Message;
                ViewBag.Status = "danger";
                return RedirectToAction("UsersList", new
                {
                    page = page,
                    rowsPerPage = rowsPerPage,
                    role = role,
                    sortOrder = sortOrder,
                    currentFilter = currentFilter,
                    searchText = searchText
                });
            }
        }

        //
        // POST: /Management/UserManager/Delete/5

        [HttpPost]
        public ActionResult DeleteUser(int id, int? page = 1,
            string rowsPerPage = "10",
            string role = null,
            string sortOrder = null,
            string currentFilter = null,
            string searchText = null)
        {
            try
            {
                if (id != default(int))
                {
                    var ids = new List<int> {id};
                    _userManager.MarkDeletedUsers(ids);
                    ViewBag.StatusMessage = "Thao tác xoá người dùng thành công.";
                }

                return RedirectToAction("UsersList", new
                {
                    page = page,
                    rowsPerPage = rowsPerPage,
                    role = role,
                    sortOrder = sortOrder,
                    currentFilter = currentFilter,
                    searchText = searchText
                });
            }
            catch
            {
                throw;
                ViewBag.StatusMessage = "Bạn chưa chọn gì để xoá.";
                ViewBag.Status = "warning";
            }
        }

        public IEnumerable<SelectListItem> GetProvinces()
        {
            const string relPath = "~/Content/Provinces.xml";
            var absPath = Server.MapPath(relPath);
            IEnumerable<SelectListItem> provinces = from proc in XDocument.Load(absPath).Descendants("Province")
                                                    select new SelectListItem
                                                    {
                                                        Text = (string)proc,
                                                        Value = (string)proc
                                                    };
            return provinces.ToList();
        }
    }
}
